import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {
  Form,
  Input,
  Switch,
  Field,
  Message,
  Balloon,
  Button,
  Radio,
  PopConfirm,
} from '@teamix/ui';
import { Header, Content, YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import ipRangeCheck from 'ip-range-check';
import ListLoading from 'atComponents/ListLoading';
import { enterPage, Perf } from 'utils/track';
import * as actions from '../actions/index';
import SwitchConfirm from './switchPopConfirm';
import docs from 'utils/docs';
import intl from '../../../../../../../../../locale';

const { remoteIP } = window.FORCE;

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

class Root extends Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      visible: false,
    };
  }

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.security.containers.root.IpAddressWhitelistYunxiaoCodeup',
      defaultMessage: 'IP 白名单 · 云效 Codeup',
    });
    this.props.getIpWhite();

    enterPage('Organization-Settings-Security', {
      sendPerf: false,
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    this.field.setErrors(nextProps.errors);
  }

  onCancel = () => {
    this.setState({
      visible: false,
    });
  };

  onVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  onIPSwitchChange = (value, type) => {
    if (!value) {
      this.props.putIpWhite({ ip_whitelist_enabled: false });
    }
    let { ip_whitelist_data } = this.props;

    if (
      Object.keys(ip_whitelist_data).length === 1 &&
      ip_whitelist_data.ip_whitelist_enabled === false
    ) {
      ip_whitelist_data = {
        ...this.props.last_ip_whitelist_data,
      };
    }
    ip_whitelist_data[type] = value;
    this.props.updateData({
      ip_whitelist_data,
    });
  };

  onIPListChange = (value, type) => {
    this.props.setErrors(this.field.getError(type));
    const { ip_whitelist_data } = this.props;
    const IPNum = value.split(',');
    ip_whitelist_data[type] = value;
    this.props.updateData({ ip_whitelist_data });
    if (IPNum.length > 1000) {
      this.openErrorMessage();
    }
  };

  onIPScopeChange = (value, type) => {
    const { ip_whitelist_data } = this.props;
    ip_whitelist_data[type] = value;
    this.props.updateData({ ip_whitelist_data });
  };

  openErrorMessage = () => {
    Message.error({
      title: intl.get({
        id: 'code-assets.security.containers.root.TheErrorMessageReturnedBecause',
        defaultMessage: '超过白名单限定数量1000',
      }),
    });
  };

  handleSubmit = () => {
    const { ip_whitelist_data } = this.props;
    const ip_white_nospace = ip_whitelist_data.ip_whitelist.split(',').map((item) => item.trim());
    ip_whitelist_data.ip_whitelist = ip_white_nospace.join(',');
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.props.checkIpWhite(ip_whitelist_data, () => {
      this.setState({ submitting: false, visible: false });
    });
  };

  componentWillUnmount() {
    this.props.resetData();
  }

  render() {
    const { ip_whitelist_data, isIPLoading, isLastIPLoading } = this.props;
    const { ip_whitelist_enabled = false, ip_whitelist, scope } = ip_whitelist_data;

    const ipValueArr = ip_whitelist && ip_whitelist.split(',').map((item) => item.trim());
    const ipValue = ipValueArr && ipValueArr.join(',');
    let warningMessage;
    if (ipValueArr && !ipValueArr.some((item) => ipRangeCheck(remoteIP, item))) {
      warningMessage = intl.get(
        {
          id: 'code-assets.security.containers.root.YourCurrentIpAddressIs',
          defaultMessage:
            '你当前的 IP 地址为 {remoteIP} ，未设置在可访问范围内，你将无法再访问本企业 Codeup 页面，请核实后提交！',
        },
        { remoteIP },
      );
    }
    if (ipValueArr && ipValueArr.length === 1 && ipValueArr[0] === '127.0.0.1') {
      warningMessage = intl.get({
        id: 'code-assets.security.containers.root.OnlyIndicatesThatAccessFrom',
        defaultMessage: '仅设置 127.0.0.1 表示禁止所有地址访问。',
      });
    }

    const isAllScope = scope === 'all';

    return (
      <>
        <Header
          title={intl.get({
            id: 'code-assets.security.containers.root.IpAddressWhitelist',
            defaultMessage: 'IP 白名单',
          })}
        />
        <Content>
          {isIPLoading || isLastIPLoading ? (
            <ListLoading />
          ) : (
            <React.Fragment>
              <Perf page="Organization-Settings-Security" />
              <Form field={this.field} labelAlign="top" className="security-form">
                <FormItem
                  {...formItemLayout}
                  label={intl.get({
                    id: 'code-assets.security.containers.root.EnableWhitelistVerification',
                    defaultMessage: '开启白名单验证',
                  })}
                >
                  <div className="ip-white-verify">
                    <span className="ip-white-verify-desc">
                      {intl.get({
                        id: 'code-assets.security.containers.root.RestrictAccessToSpecificIp',
                        defaultMessage:
                          '限制特定 IP 网段的访问，开启后白名单之外的访问均会被阻止，以增强企业数据安全性',
                      })}
                    </span>
                    <SwitchConfirm
                      trigger={
                        <Switch
                          className="ip-white-verify-switch"
                          name="ip_whitelist_enabled"
                          checked={ip_whitelist_enabled}
                        />
                      }
                      onChange={(value) => {
                        this.onIPSwitchChange(value, 'ip_whitelist_enabled');
                      }}
                      needPopConfirm={ip_whitelist_enabled}
                    />
                  </div>
                </FormItem>
                {ip_whitelist_enabled && (
                  <FormItem
                    {...formItemLayout}
                    label={intl.get({
                      id: 'code-assets.security.containers.root.ScopeOfAction',
                      defaultMessage: '作用范围',
                    })}
                    required
                  >
                    <div className="ip-white-scope">
                      <Radio.Group
                        value={scope}
                        onChange={(value) => {
                          this.onIPScopeChange(value, 'scope');
                        }}
                        itemDirection="ver"
                        size="small"
                      >
                        <Radio value="all">
                          {intl.get({
                            id: 'code-assets.security.containers.root.AllOperationsIncludingCodeupPage',
                            defaultMessage:
                              '全部（包括 Codeup 页面访问、部署密钥访问、代码克隆、下载、提交、合并等行为）',
                          })}
                        </Radio>
                        <Radio value="deploykey">
                          {intl.get({
                            id: 'code-assets.security.containers.root.DeployKeyAccess',
                            defaultMessage: '部署密钥访问',
                          })}

                          <Balloon
                            closable={false}
                            type="normal"
                            trigger={
                              <ButtonIcon
                                text
                                name="question-line"
                                style={{ marginLeft: 4, display: 'inline-block' }}
                              />
                            }
                            align="t"
                          >
                            {intl.get({
                              id: 'code-assets.security.containers.root.IpAddressesOutsideTheWhitelist',
                              defaultMessage: '禁止白名单之外的 IP 使用部署密钥访问企业代码库，',
                            })}

                            <a href={docs('deploymentKey')} target="_blank" rel="noreferrer">
                              {intl.get({
                                id: 'code-assets.security.containers.root.ViewDeploymentKeyInstructions',
                                defaultMessage: '查看部署密钥使用说明',
                              })}
                            </a>
                          </Balloon>
                        </Radio>
                      </Radio.Group>
                    </div>
                  </FormItem>
                )}

                {ip_whitelist_enabled && (
                  <FormItem
                    className="ip-whitelist"
                    label={intl.get({
                      id: 'code-assets.security.containers.root.AccessibleIpAddresses',
                      defaultMessage: '可访问 IP',
                    })}
                    required
                    requiredMessage={intl.get({
                      id: 'code-assets.security.containers.root.IpAddressIsRequired',
                      defaultMessage: 'IP 是必填项',
                    })}
                    format="ip_whitelist"
                    extra={
                      <div className="security-extra">
                        {isAllScope ? (
                          <React.Fragment>
                            <div>
                              <YunxiaoIcon
                                type="warning-fill"
                                size="small"
                                style={{ color: '#FFA003', marginRight: '5px' }}
                              />
                              {intl.get({
                                id: 'code-assets.security.containers.root.YourCurrentIpAddressIs.2',
                                defaultMessage: '你当前 IP 为',
                              })}{' '}
                              <span className="remote-ip">{remoteIP}</span>
                              {intl.get({
                                id: 'code-assets.security.containers.root.AddItToAnIp',
                                defaultMessage:
                                  '，\n                                请将其加入允许访问的 IP ，否则即使作为管理员也无法再次访问 Codeup。',
                              })}
                            </div>
                            <div>
                              <YunxiaoIcon
                                type="warning-fill"
                                size="small"
                                style={{ color: '#FFA003', marginRight: '5px' }}
                              />
                              {intl.get({
                                id: 'code-assets.security.containers.root.IfYouUseAFlow',
                                defaultMessage:
                                  '如使用 Flow 或其他第三方集成服务，请将其加入允许访问的 IP ，否则可能导致服务运行异常。',
                              })}

                              <a target="_blank" href={docs('getFlowIp')} rel="noreferrer">
                                {intl.get({
                                  id: 'code-assets.security.containers.root.HowDoIObtainFlow',
                                  defaultMessage: '如何获取 Flow IP ？',
                                })}
                              </a>
                            </div>
                          </React.Fragment>
                        ) : (
                          <React.Fragment>
                            <div>
                              <YunxiaoIcon
                                type="warning-fill"
                                size="small"
                                style={{ color: '#FFA003', marginRight: '5px' }}
                              />
                              {intl.get({
                                id: 'code-assets.security.containers.root.YourCurrentIpAddressIs.2',
                                defaultMessage: '你当前 IP 为',
                              })}

                              <span className="remote-ip">{remoteIP}</span>
                            </div>
                            <div>
                              <YunxiaoIcon
                                type="warning-fill"
                                size="small"
                                style={{ color: '#FFA003', marginRight: '5px' }}
                              />
                              {intl.get({
                                id: 'code-assets.security.containers.root.AddTheIpAddressesThat',
                                defaultMessage:
                                  '将需要使用部署密钥访问的 IP 加入允许访问范围，否则将无法通过部署密钥访问代码库',
                              })}
                            </div>
                          </React.Fragment>
                        )}

                        <div>
                          <span>•</span>
                          {intl.get({
                            id: 'code-assets.security.containers.root.SeparateMultipleIpAddressesWith',
                            defaultMessage: '多个 IP 用英文逗号隔开，逗号前后不加空格。',
                          })}
                        </div>
                        <div>
                          <span>•</span>
                          {intl.get({
                            id: 'code-assets.security.containers.root.SetToAllowAllAddresses',
                            defaultMessage: '设置 0.0.0.0/0 表示允许所有地址',
                          })}
                          {isAllScope
                            ? ''
                            : intl.get({
                                id: 'code-assets.security.containers.root.DeployAKey',
                                defaultMessage: '通过部署密钥',
                              })}
                          {intl.get({
                            id: 'code-assets.security.containers.root.Access',
                            defaultMessage: '访问。',
                          })}
                        </div>
                        <div>
                          <span>•</span>
                          {intl.get({
                            id: 'code-assets.security.containers.root.OnlyIndicatesThatAllAddresses',
                            defaultMessage: '仅设置 127.0.0.1 表示禁止所有地址',
                          })}
                          {isAllScope
                            ? ''
                            : intl.get({
                                id: 'code-assets.security.containers.root.DeployAKey',
                                defaultMessage: '通过部署密钥',
                              })}
                          {intl.get({
                            id: 'code-assets.security.containers.root.Access',
                            defaultMessage: '访问。',
                          })}
                        </div>
                        <div>
                          <span>•</span>
                          {intl.get({
                            id: 'code-assets.security.containers.root.SetTheCidrBlockTo',
                            defaultMessage:
                              '设置 IP 段表示该网段内的 IP\n                        地址都可以',
                          })}
                          {isAllScope
                            ? ''
                            : intl.get({
                                id: 'code-assets.security.containers.root.DeployAKey',
                                defaultMessage: '通过部署密钥',
                              })}
                          {intl.get({
                            id: 'code-assets.security.containers.root.Access.1',
                            defaultMessage: '访问',
                          })}
                          {isAllScope
                            ? intl.get({
                                id: 'code-assets.security.containers.root.TheEnterpriseCodeLibrary',
                                defaultMessage: '该企业内代码库',
                              })
                            : ''}
                          {intl.get({
                            id: 'code-assets.security.containers.root.ForExample',
                            defaultMessage: '，如 10.10.10.0/24。',
                          })}
                        </div>
                      </div>
                    }
                  >
                    <Input.TextArea
                      required
                      name="ip_whitelist"
                      value={ipValue}
                      onChange={(value) => {
                        this.onIPListChange(value, 'ip_whitelist');
                      }}
                      placeholder={
                        remoteIP
                          ? intl.get(
                              {
                                id: 'code-assets.security.containers.root.ForExampleRemoteip',
                                defaultMessage: '例如：{remoteIP},203.107.52.79',
                              },
                              { remoteIP },
                            )
                          : '203.107.52.79'
                      }
                    />
                  </FormItem>
                )}
                <FormItem>
                  {ip_whitelist_enabled && (
                    <React.Fragment>
                      {ip_whitelist && scope ? (
                        <React.Fragment>
                          {!ipValueArr.includes('0.0.0.0/0') && warningMessage && isAllScope ? (
                            <PopConfirm
                              type="danger"
                              triggerType="click"
                              align="t"
                              title={intl.get({
                                id: 'code-assets.security.containers.root.ConfirmToSave',
                                defaultMessage: '确认保存',
                              })}
                              content={warningMessage}
                              trigger={
                                <Form.Submit type="primary">
                                  {intl.get({
                                    id: 'code-assets.security.containers.root.Save',
                                    defaultMessage: '保存',
                                  })}
                                </Form.Submit>
                              }
                              onConfirm={this.handleSubmit}
                              onCancel={this.onCancel}
                              visible={this.state.visible}
                              onVisibleChange={this.onVisibleChange}
                            />
                          ) : (
                            <Form.Submit
                              type="primary"
                              onClick={this.handleSubmit}
                              loading={this.state.submitting}
                            >
                              {intl.get({
                                id: 'code-assets.security.containers.root.Save',
                                defaultMessage: '保存',
                              })}
                            </Form.Submit>
                          )}
                        </React.Fragment>
                      ) : (
                        <Balloon.Tooltip
                          trigger={
                            <Button type="primary" disabled>
                              {intl.get({
                                id: 'code-assets.security.containers.root.Save',
                                defaultMessage: '保存',
                              })}
                            </Button>
                          }
                          align="t"
                        >
                          {intl.get({
                            id: 'code-assets.security.containers.root.ExistRequiredNotFilledIn',
                            defaultMessage: '存在必填项未填写',
                          })}
                        </Balloon.Tooltip>
                      )}
                    </React.Fragment>
                  )}
                </FormItem>
              </Form>
            </React.Fragment>
          )}
        </Content>
      </>
    );
  }
}

export default connect(
  (state) => state.organization.settings.security,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
